<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Home extends MY_Controller {

	public function _remap($method){
		$this->carabiner->css(array(
				array('base.css', 'screen')
		));
		$this->carabiner->js(array(
				array('libs/jquery.min.js'),
				array('libs/jquery-ui.js'),
				array('alertas.js'),
				array('libs/jquery.notify.min.js'),
		));

		$this->{$method}();
	}

	public function index()
	{
    if($this->session->userdata('id_usuario'))
    {
      if ($this->session->userdata['tipo'] === 'tic')
        redirect(base_url('tic/'));
      else
        redirect(base_url('free/'));
    }

		$this->carabiner->css(array(
			array('libs/jquery.tinyscroll.css', 'screen'),
			array('libs/ui.notify.css', 'screen'),
			array('libs/jquery.slider.css', 'screen'),
			array('libs/jquery.superbox.css', 'screen'),
			array('home.css', 'screen')
		));
		$this->carabiner->js(array(
				array('libs/jquery.html5placeholder.js'),
				array('libs/jquery.tinyscrollbar.min.js'),
				array('libs/jquery.slides.min.js'),
				array('libs/jquery.superbox.js'),
        array('http://connect.facebook.net/en_US/all.js'),
				array('home/home.js')
		));

		$params['seo'] = array('titulo' => 'Tienda Capp breviarios, articulos, infografias de política pública',
			'description' => 'Análisis mensual de temas de interés sobre Colima. Dos páginas de conocimiento preciso para tomadores de decisiones. Relevantes estadísticas, datos e información acerca de Colima.');

		if (isset($_POST['entrar']))
			$fun_res = $this->registro();
		if (isset($_POST['tic']) || isset($_POST['free']))
			$fun_res = $this->login();

		if (isset($fun_res['frm_errors'])){
			$params['frm_errors'] = $fun_res['frm_errors'];
		}

		$params['organiza'] = $this->db
			->select('id_organizacion, nombre, estudiante')
			->from('organizaciones')
			->order_by('nombre', 'ASC')
			->get()->result();

    if (isset($_GET['msg'])) {
      $params['frm_errors'] = $this->showMsgs($_GET['msg'], 'Error');
    }

    $this->load->library('my_facebook');
    $params['fb_app_id'] = $this->my_facebook->APP_ID;
    $params['username'] = $this->session->userdata('nombre');

    //Carga links de abajo
    $_GET['cat'] = 'bpp';
    $_GET['ho'] = 'si';
    $params['tt_bpp'] = $this->articulos();
    $_GET['cat'] = 'cp';
    $params['tt_cp'] = $this->articulos();
    $_GET['cat'] = 'bd';
    $params['tt_bd'] = $this->articulos();

		$this->load->view('skin/header', $params);
		$this->load->view('skin/home', $params);
		$this->load->view('skin/footer');
	}

	/*
	|	muestra el contador
	*/
	public function cangea_countdown()
	{
		$this->carabiner->css(array(
			array('libs/jquery.countdown.css', 'screen')
		));
		$this->carabiner->js(array(
				array('libs/jquery.countdown.js')
		));

		$this->load->view('skin/home/carga_countdown');
	}

	public function faqs(){
		if ($this->input->get('tic') == 'si') {
			$params['html'] = $this->load->view('skin/home/faqs', array(), true);
			echo json_encode($params);
		}elseif ($this->input->get('ho') == 'si') {
			$this->load->view('skin/home/faqs');
		}else{
			$this->carabiner->css(array(
				array('libs/jquery.tinyscroll.css', 'screen'),
				array('libs/ui.notify.css', 'screen'),
				array('libs/jquery.slider.css', 'screen'),
				array('home.css', 'screen')
			));
			$this->carabiner->js(array(
					array('libs/jquery.html5placeholder.js'),
					array('libs/jquery.tinyscrollbar.min.js'),
					array('libs/jquery.slides.min.js'),
					array('http://connect.facebook.net/en_US/all.js'),
					array('home/home.js')
			));

			$params['seo'] = array('titulo' => 'Tienda Capp - Preguntas Frecuentes');

			if (isset($_POST['entrar']))
				$fun_res = $this->registro();
			if (isset($_POST['tic']) || isset($_POST['free']))
				$fun_res = $this->login();

			if (isset($fun_res['frm_errors'])){
				$params['frm_errors'] = $fun_res['frm_errors'];
			}

			$params['organiza'] = $this->db
				->select('id_organizacion, nombre, estudiante')
				->from('organizaciones')
				->order_by('nombre', 'ASC')
				->get()->result();

	    if (isset($_GET['msg'])) {
	      $params['frm_errors'] = $this->showMsgs($_GET['msg'], 'Error');
	    }

	    $this->load->library('my_facebook');
	    $params['fb_app_id'] = $this->my_facebook->APP_ID;
	    $params['username'] = $this->session->userdata('nombre');
	    //Carga links de abajo
	    $_GET['cat'] = 'bpp';
	    $_GET['ho'] = 'si';
	    $params['tt_bpp'] = $this->articulos();
	    $_GET['cat'] = 'cp';
	    $params['tt_cp'] = $this->articulos();
	    $_GET['cat'] = 'bd';
	    $params['tt_bd'] = $this->articulos();


	    $params['faqs'] = $this->load->view('skin/home/faqs', $params, true);
			$this->load->view('skin/header', $params);
			$this->load->view('skin/home', $params);
			$this->load->view('skin/footer');
		}
	}

	public function about(){
		if ($this->input->get('tic') == 'si') {
			$params['html'] = $this->load->view('skin/home/about', array(), true);
			echo json_encode($params);
		}elseif ($this->input->get('ho') == 'si') {
			$this->load->view('skin/home/about');
		}else{
			$this->carabiner->css(array(
				array('libs/jquery.tinyscroll.css', 'screen'),
				array('libs/ui.notify.css', 'screen'),
				array('libs/jquery.slider.css', 'screen'),
				array('home.css', 'screen')
			));
			$this->carabiner->js(array(
					array('libs/jquery.html5placeholder.js'),
					array('libs/jquery.tinyscrollbar.min.js'),
					array('libs/jquery.slides.min.js'),
					array('http://connect.facebook.net/en_US/all.js'),
					array('home/home.js')
			));

			$params['seo'] = array('titulo' => 'Tienda Capp - Acerca de Tienda de Conocimiento Capp');

			if (isset($_POST['entrar']))
				$fun_res = $this->registro();
			if (isset($_POST['tic']) || isset($_POST['free']))
				$fun_res = $this->login();

			if (isset($fun_res['frm_errors'])){
				$params['frm_errors'] = $fun_res['frm_errors'];
			}

			$params['organiza'] = $this->db
				->select('id_organizacion, nombre, estudiante')
				->from('organizaciones')
				->order_by('nombre', 'ASC')
				->get()->result();

	    if (isset($_GET['msg'])) {
	      $params['frm_errors'] = $this->showMsgs($_GET['msg'], 'Error');
	    }

	    $this->load->library('my_facebook');
	    $params['fb_app_id'] = $this->my_facebook->APP_ID;
	    $params['username'] = $this->session->userdata('nombre');
	    //Carga links de abajo
	    $_GET['cat'] = 'bpp';
	    $_GET['ho'] = 'si';
	    $params['tt_bpp'] = $this->articulos();
	    $_GET['cat'] = 'cp';
	    $params['tt_cp'] = $this->articulos();
	    $_GET['cat'] = 'bd';
	    $params['tt_bd'] = $this->articulos();


	    $params['about'] = $this->load->view('skin/home/about', $params, true);
			$this->load->view('skin/header', $params);
			$this->load->view('skin/home', $params);
			$this->load->view('skin/footer');
		}
	}

	public function terminos(){
		if ($this->input->get('ho') == 'si') {
			$this->load->view('skin/home/terminos');
		}else{
			$this->carabiner->css(array(
				array('libs/jquery.tinyscroll.css', 'screen'),
				array('libs/ui.notify.css', 'screen'),
				array('libs/jquery.slider.css', 'screen'),
				array('home.css', 'screen')
			));
			$this->carabiner->js(array(
					array('libs/jquery.html5placeholder.js'),
					array('libs/jquery.tinyscrollbar.min.js'),
					array('libs/jquery.slides.min.js'),
					array('http://connect.facebook.net/en_US/all.js'),
					array('home/home.js')
			));

			$params['seo'] = array('titulo' => 'Tienda Capp - Términos y Condiciones de Uso');

			if (isset($_POST['entrar']))
				$fun_res = $this->registro();
			if (isset($_POST['tic']) || isset($_POST['free']))
				$fun_res = $this->login();

			if (isset($fun_res['frm_errors'])){
				$params['frm_errors'] = $fun_res['frm_errors'];
			}

			$params['organiza'] = $this->db
				->select('id_organizacion, nombre, estudiante')
				->from('organizaciones')
				->order_by('nombre', 'ASC')
				->get()->result();

	    if (isset($_GET['msg'])) {
	      $params['frm_errors'] = $this->showMsgs($_GET['msg'], 'Error');
	    }

	    $this->load->library('my_facebook');
	    $params['fb_app_id'] = $this->my_facebook->APP_ID;
	    $params['username'] = $this->session->userdata('nombre');
	    //Carga links de abajo
	    $_GET['cat'] = 'bpp';
	    $_GET['ho'] = 'si';
	    $params['tt_bpp'] = $this->articulos();
	    $_GET['cat'] = 'cp';
	    $params['tt_cp'] = $this->articulos();
	    $_GET['cat'] = 'bd';
	    $params['tt_bd'] = $this->articulos();

	    $params['terminos'] = $this->load->view('skin/home/terminos', $params, true);
			$this->load->view('skin/header', $params);
			$this->load->view('skin/home', $params);
			$this->load->view('skin/footer');
		}
	}

	public function precios(){
		$this->load->view('skin/home/precios');
	}

	public function articulos(){
		$_GET['cat'] = $this->input->get("cat")!=''? $this->input->get("cat"): 'bpp';
		switch ($_GET['cat']) {
			case 'bpp':
				$cat = 1;
				$title = 'Breviarios de Política Pública';
				break;
			case 'cp':
				$cat = 2;
				$title = 'Capp Propone';
				break;
			case 'bd':
				$cat = 3;
				$title = 'Bases de Datos';
				break;
			default:
				$cat = 1;
				$title = 'Breviarios de Política Pública';
		}
		$params['articulos1'] = $this->db->query("SELECT a.id_articulo, a.numero, a.titulo,
				a.descripcion, a.fecha_creacion, a.fecha_actualizacion, a.materia, a.variables,
				a.url_archivo, a.status, at.id_tipo, at.nombre
			FROM articulos AS a
				INNER JOIN articulos_tipo AS at ON a.id_tipo = at.id_tipo
			WHERE a.status = 1 AND at.id_tipo = ".$cat."
			ORDER BY a.numero ASC")->result();

		if ($this->input->get('ho') == 'si') {
			$template = $this->load->view('skin/home/articulos'.$cat, $params, true);
			return $template;
			// header("Content-type: application/json");
			// echo json_encode(array('html' => $template));
		}else{
			$this->carabiner->css(array(
				array('libs/jquery.tinyscroll.css', 'screen'),
				array('libs/ui.notify.css', 'screen'),
				array('libs/jquery.slider.css', 'screen'),
				array('home.css', 'screen')
			));
			$this->carabiner->js(array(
					array('libs/jquery.html5placeholder.js'),
					array('libs/jquery.tinyscrollbar.min.js'),
					array('libs/jquery.slides.min.js'),
					array('http://connect.facebook.net/en_US/all.js'),
					array('home/home.js')
			));

			$params['seo'] = array('titulo' => 'Tienda Capp - '.$title);

			if (isset($_POST['entrar']))
				$fun_res = $this->registro();
			if (isset($_POST['tic']) || isset($_POST['free']))
				$fun_res = $this->login();

			if (isset($fun_res['frm_errors'])){
				$params['frm_errors'] = $fun_res['frm_errors'];
			}

			$params['organiza'] = $this->db
				->select('id_organizacion, nombre, estudiante')
				->from('organizaciones')
				->order_by('nombre', 'ASC')
				->get()->result();

	    if (isset($_GET['msg'])) {
	      $params['frm_errors'] = $this->showMsgs($_GET['msg'], 'Error');
	    }

	    $this->load->library('my_facebook');
	    $params['fb_app_id'] = $this->my_facebook->APP_ID;
	    $params['username'] = $this->session->userdata('nombre');

	    $params['articulos'] = $this->load->view('skin/home/articulos'.$cat, $params, true);


	    //Carga links de abajo
	    $_GET['cat'] = 'bpp';
	    $_GET['ho'] = 'si';
	    $params['tt_bpp'] = $this->articulos();
	    $_GET['cat'] = 'cp';
	    $params['tt_cp'] = $this->articulos();
	    $_GET['cat'] = 'bd';
	    $params['tt_bd'] = $this->articulos();

			$this->load->view('skin/header', $params);
			$this->load->view('skin/home', $params);
			$this->load->view('skin/footer');
		}
	}


	/*
	| Registro de Usuarios o completar registro de usuarios
	*/
	public function registro($completar_registro = FALSE)
	{
			$this->load->model('usuarios_model');
			$this->configRegistro($completar_registro);
			if ($this->form_validation->run() == FALSE)
				return array('frm_errors' => array('title'=>'Error', 'msg'=>preg_replace("[\n|\r|\n\r]", '', validation_errors()),'ico'=>'error'));
			else
			{
				if ($completar_registro == FALSE)
					$mdl_res = $this->usuarios_model->setRegistro();
				else
				{

					$_POST['forganizacion']     = $_POST['tipo_organizacion'];
					$_POST['fnombre']           = $_POST['nombre'];
					$_POST['femail']            = $_POST['email'];
					$_POST['fusuario']          = '';
					$_POST['fpass']             = $_POST['pass'];
					$_POST['ffecha_nacimiento'] = date('Y-m-d h:i:s',  mktime(0,0,0, $_POST['fn_mes'], $_POST['fn_dia'], $_POST['fn_anio']));
					$_POST['ftipo']             = 'usuario';

					$id_usuario = $this->session->userdata('id_usuario');
					$mdl_res    = $this->usuarios_model->modificar_usuario($id_usuario);

					return TRUE;
				}

				if ($mdl_res['error'] == FALSE) {
						// Si se registra correctamente crea la session y de redirecciona
					$data = "(email='".$this->input->post('email')."' OR usuario='".$this->input->post('email')."') AND pass='".$this->input->post('pass')."' AND status='1' ";
					$mdl_res = $this->usuarios_model->setLogin($data);
					redirect(base_url('free'));
				}
			}
	}

	/*
	| Login de Usuarios
	*/
	public function login()
	{
		$this->configLogin();
		if ($this->form_validation->run() == FALSE)
			return array('frm_errors' => array('title'=>'Error', 'msg'=>preg_replace("[\n|\r|\n\r]", '', validation_errors()), 'ico'=>'error'));
		else
		{
			$this->load->model('usuarios_model');
			// $data    = array('email'=>$this->input->post('email'), 'pass'=>$this->input->post('password'));
			$data = "(email='".$this->input->post('email')."' OR usuario='".$this->input->post('email')."') AND pass='".$this->input->post('password')."' AND status='1' ";
			$mdl_res = $this->usuarios_model->setLogin($data);

			if ($mdl_res[0])
				redirect(base_url());

			// $msg = 'El correo electrónico y/o contraseña son incorrectos';
			if (isset($mdl_res['msg']))
				$msg = $mdl_res['msg'];

			return array('frm_errors' => array('title'=>'Error', 'msg'=>preg_replace("[\n|\r|\n\r]", '', $msg), 'ico'=>'error'));
		}
	}

	/*
	| Logout de Usuarios
	| Elimina los parametros de usuario en la session
	*/
	public function logout()
	{
		$this->session->sess_destroy();

		// $unset_data = array(	'id_usuario'=> '',
		// 											'username'  => '',
		// 											'email'     => '',
		// 											'tipo'			=> '',
		// 											'logged_in' => '');
		// $this->session->unset_userdata($unset_data);
		redirect(base_url());
	}

	/*
	| Valida los campos del login
	*/
	public function configLogin()
	{
		$this->load->library('form_validation');
		$rules = array(
							array('field' => 'email',
										'label' => 'Correo Electrónico',
										'rules' => 'required|max_length[70]'), //|valid_email
							array('field' => 'password',
										'label' => 'Contraseña',
										'rules' => 'required|max_length[35]'));

		$this->form_validation->set_rules($rules);
	}

	/*
	| Valida los campos del formulario de Registro
	*/
	public function configRegistro($completar_registro)
	{
		$this->load->library('form_validation');
		$rules = array(
							array('field' => 'nombre',
										'label' => 'Nombre',
										'rules' => 'required|max_length[110]'),
							array('field' => 'tipo_organizacion',
										'label' => 'Tipo Organización',
										'rules' => 'required'),
							array('field' => 'pass',
										'label' => 'Contraseña',
										'rules' => 'required|max_length[35]|matches[pass_confirm]'),
							array('field' => 'pass_confirm',
										'label' => 'Confirma contraseña',
										'rules' => 'required'),
							array('field' => 'fn_dia',
										'label' => 'Día',
										'rules' => 'required'),
							array('field' => 'fn_mes',
										'label' => 'Mes',
										'rules' => 'required'),
							array('field' => 'fn_anio',
										'label' => 'Año',
										'rules' => 'required'));

		if ($completar_registro)
		{
			$rules[] = 	array('field' => 'email',
												'label' => 'Correo Electrónico',
												'rules' => 'required|max_length[70]|valid_email|callback_valida_email');
		}
		else
		{
			$rules[] = array('field' => 'email',
											'label' => 'Correo Electrónico',
											'rules' => 'required|max_length[70]|valid_email|callback_valida_email2');
		}

		$this->form_validation->set_rules($rules);
	}

	public function valida_email2($email)
	{
		$sql_res = $this->db->select("id_usuario")
													->from('usuarios')
													->where('email', $email)
													->where('status', '1')
													->get();
		if ($sql_res->num_rows() > 0) {
			$this->form_validation->set_message('valida_email2', 'El %s no esta disponible, intenta con otro.');
			return FALSE;
		}
		return TRUE;
	}
	public function valida_email($email)
	{
		$id_usuario = $this->session->userdata('id_usuario');
		if (!$this->usuarios_model->valida_email('usuarios',array('id_usuario'=>$id_usuario, 'email'=>$email))) {
			$this->form_validation->set_message('valida_email', 'El %s no esta disponible, intenta con otro.');
			return FALSE;
		}
		return TRUE;
	}

	/*
	|	Muestra el formulario en superbox para completar el registro del usuario
	|		si se registro por facebook o twitter
	*/
	public function registro_flotante()
	{

		$this->carabiner->css(array(
			array('libs/ui.notify.css', 'screen'),
			array('home.css', 'screen')
		));

		$params['seo'] = array('titulo' => 'Tienda Capp');

		if (isset($_POST['entrar'])){
				$fun_res = $this->registro(TRUE);

				if (! is_array($fun_res)){
					$params['reload'] = TRUE;
					$params['frm_errors'] = array('title'=>'', 'msg'=>preg_replace("[\n|\r|\n\r]", '', 'Registro completo!'), 'ico'=>'ok');
				}
		}

		if (isset($fun_res['frm_errors'])){
			$params['frm_errors'] = $fun_res['frm_errors'];
		}

		$this->load->model('usuarios_model');
		$id_usuario = $this->session->userdata('id_usuario');
		$params['info'] = $this->usuarios_model->get_usuario_info($id_usuario, TRUE);

		$params['organiza'] = $this->db
			->select('id_organizacion, nombre, estudiante')
			->from('organizaciones')
			->order_by('nombre', 'ASC')
			->get()->result();

		$this->load->view('skin/registro_flotante.php', $params);
	}

	/*
	|	Muestra el formulario en superbox para cangear el regalo de cuenta
	|		si se registro por facebook o twitter
	*/
	public function cangea_regalo()
	{
		$params['seo'] = array('titulo' => 'Tienda Capp');

		//si se envia el form de reclamo, se crea un paquete de 15 dias
		if ($this->input->post('reclamar') == 'Reclamar') {
			$this->load->model('paquetes_model');
			$paquete = array();
			$paquete['data'] = array('id_usuario' 					=> $this->session->userdata('id_usuario'),
																'fecha_vencimiento'   => String::suma_fechas(date("Y-m-d"), 15),
																'usuarios_permitidos' => '1',
																'tipo'                => 'todo',
																'status'              => '1',
																'costo'               => 0,
																'forma_pago'          => 'Regalo',
																'meses'               => '1');

			$params['id_paquete'] = $this->paquetes_model->agregar_paquete($paquete, false);

			$this->session->unset_userdata(array('tipo'=>''));
			$this->session->set_userdata(array('tipo'=>'tic'));

			$params['redirectt'] = base_url('tic');
		}else{
			$this->carabiner->css(array(
				array('libs/ui.notify.css', 'screen'),
				array('home.css', 'screen')
			));
		}

		$this->load->view('skin/free/cangea_regalo', $params);
	}


	/*
	|	AJAX
	|	Metodo llamada desde ajax para verificar si el usuario tiene completo su registro
	*/
	public function ajaxVerificaUsuarioRegistroCompleto()
	{
		$this->load->model('usuarios_model');
		$id_usuario = $this->session->userdata('id_usuario');
		$mdl_res    = $this->usuarios_model->verifica_registro_completo($id_usuario);

		echo $mdl_res;
	}

  private function showMsgs($msg, $title='Compra')
  {
    $txt='';
    $icono='';
    switch($msg){
      case 1:
        $txt = 'Error al intentar conectarte con facebook. Tu cuenta a sido eliminada.';
        $icono = 'error';
        break;
      case 2:
        $txt = 'Error al intentar conectarte con twitter. Tu cuenta a sido eliminada.';
        $icono = 'error';
        break;
      case 3:
        $txt = 'Ya existe un usuario logueado con esta cuenta.';
        $icono = 'error';
        break;
    }

    return array(
        'title' => $title,
        'msg' => $txt,
        'ico' => $icono);
  }

}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */